package cn.yfj.basic.util;

import cn.yfj.basic.jwt.JwtUtils;
import cn.yfj.basic.jwt.LoginData;
import cn.yfj.basic.jwt.Payload;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

public class LoginContext {
    public static final String PUBKEY = "hrm_auth_rsa.pub";


    public static Object getLogin(HttpServletRequest request){
        //获取jwt  token
        String jwtToken = request.getHeader("U-TOKEN");
        if(StringUtils.isEmpty(jwtToken)){
            return null;
        }
        //获取公钥
        try {
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource(PUBKEY).getFile());
            Payload<LoginData> payload = JwtUtils.getInfoFromToken(jwtToken, publicKey, LoginData.class);
            LoginData loginData = payload.getLoginData();
            //解密jwt，得到载荷数据
            //从载荷数据中获取登录信息
            return loginData.getUser() != null ? loginData.getUser() : loginData.getAdmin();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
